<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,">










<meta name="description" content="泛型在转换成字节码的时候, 还是Object类似,  在获取对象的时候还是进行了一下 强制类型转换 使用&amp;lt;? &amp;gt;表示泛型不确定, 所以使用? 的类中, 有关泛型的操作方法和变量都无法运行和赋值.   可以使用&amp;lt;? extends String&amp;gt; 来限定泛型的范围, 这样限定后, 转换成字节码的泛型不再是Object的,而是String  泛型，一个孤独的守门者。 大家可">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="java的泛型详解">
<meta property="og:url" content="https://blog.xiezc.xyz/2019/03/22/java/java的泛型详解/index.html">
<meta property="og:site_name" content="xiezc的小站">
<meta property="og:description" content="泛型在转换成字节码的时候, 还是Object类似,  在获取对象的时候还是进行了一下 强制类型转换 使用&amp;lt;? &amp;gt;表示泛型不确定, 所以使用? 的类中, 有关泛型的操作方法和变量都无法运行和赋值.   可以使用&amp;lt;? extends String&amp;gt; 来限定泛型的范围, 这样限定后, 转换成字节码的泛型不再是Object的,而是String  泛型，一个孤独的守门者。 大家可">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-04-04T15:57:09.025Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java的泛型详解">
<meta name="twitter:description" content="泛型在转换成字节码的时候, 还是Object类似,  在获取对象的时候还是进行了一下 强制类型转换 使用&amp;lt;? &amp;gt;表示泛型不确定, 所以使用? 的类中, 有关泛型的操作方法和变量都无法运行和赋值.   可以使用&amp;lt;? extends String&amp;gt; 来限定泛型的范围, 这样限定后, 转换成字节码的泛型不再是Object的,而是String  泛型，一个孤独的守门者。 大家可">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.xiezc.xyz/2019/03/22/java/java的泛型详解/">





  <title>java的泛型详解 | xiezc的小站</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8ae02d8cf311eabbae2621ff2d51a260";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xiezc的小站</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">xiezc的小站</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.xiezc.xyz/2019/03/22/java/java的泛型详解/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xiezc">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xiezc的小站">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java的泛型详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-22T16:21:33+08:00">
                2019-03-22
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/03/22/java/java的泛型详解/" class="leancloud_visitors" data-flag-title="java的泛型详解">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p> 泛型在转换成字节码的时候, 还是Object类似,  在获取对象的时候还是进行了一下 强制类型转换</p>
<p>使用&lt;? &gt;表示泛型不确定, 所以使用? 的类中, 有关泛型的操作方法和变量都无法运行和赋值.  </p>
<p>可以使用&lt;? extends String&gt; 来限定泛型的范围, 这样限定后, 转换成字节码的泛型不再是Object的,而是String</p>
</blockquote>
<p><strong>泛型，一个孤独的守门者。</strong></p>
<p>大家可能会有疑问，我为什么叫做泛型是一个守门者。这其实是我个人的看法而已，我的意思是说泛型没有其看起来那么深不可测，它并不神秘与神奇。泛型是 Java 中一个很小巧的概念，但同时也是一个很容易让人迷惑的知识点，它让人迷惑的地方在于它的许多表现有点违反直觉。</p>
<p>文章开始的地方，先给大家奉上一道经典的测试题。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; l1 = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">List&lt;Integer&gt; l2 = <span class="keyword">new</span> ArrayList&lt;Integer&gt;();</span><br><span class="line">	</span><br><span class="line">System.out.println(l1.getClass() == l2.getClass());</span><br></pre></td></tr></table></figure>
<p>请问，上面代码最终结果输出的是什么？不了解泛型的和很熟悉泛型的同学应该能够答出来，而对泛型有所了解，但是了解不深入的同学可能会答错。</p>
<p>正确答案是 true。</p>
<p>上面的代码中涉及到了泛型，而输出的结果缘由是类型擦除。先好好说说泛型。</p>
<p>##泛型是什么？</p>
<p>泛型的英文是 generics，generic 的意思是通用,而翻译成中文，泛应该意为广泛，型是类型。所以泛型就是能广泛适用的类型。</p>
<p>但泛型还有一种较为准确的说法就是为了参数化类型，或者说可以将类型当作参数传递给一个类或者是方法。</p>
<p>那么，如何解释类型参数化呢？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cache</span> </span>&#123;</span><br><span class="line">	Object value;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">getValue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(Object value)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>假设 Cache 能够存取任何类型的值，于是，我们可以这样使用它。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Cache cache = <span class="keyword">new</span> Cache();</span><br><span class="line">cache.setValue(<span class="number">134</span>);</span><br><span class="line"><span class="keyword">int</span> value = (<span class="keyword">int</span>) cache.getValue();</span><br><span class="line">cache.setValue(<span class="string">"hello"</span>);</span><br><span class="line">String value1 = (String) cache.getValue();</span><br></pre></td></tr></table></figure>
<p>使用的方法也很简单，只要我们做正确的强制转换就好了。</p>
<p>但是，泛型却给我们带来了不一样的编程体验。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cache</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">	T value;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Object <span class="title">getValue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> value;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(T value)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.value = value;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<p>这就是泛型，它将 value 这个属性的类型也参数化了，这就是所谓的参数化类型。再看它的使用方法。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Cache&lt;String&gt; cache1 = <span class="keyword">new</span> Cache&lt;String&gt;();</span><br><span class="line">cache1.setValue(<span class="string">"123"</span>);</span><br><span class="line">String value2 = cache1.getValue();</span><br><span class="line">		</span><br><span class="line">Cache&lt;Integer&gt; cache2 = <span class="keyword">new</span> Cache&lt;Integer&gt;();</span><br><span class="line">cache2.setValue(<span class="number">456</span>);</span><br><span class="line"><span class="keyword">int</span> value3 = cache2.getValue();</span><br></pre></td></tr></table></figure></p>
<p>最显而易见的好处就是它不再需要对取出来的结果进行强制转换了。但，还有另外一点不同。</p>
<p>泛型除了可以将类型参数化外，而参数一旦确定好，如果类似不匹配，编译器就不通过。<br>上面代码显示，无法将一个 String 对象设置到 cache2 中，因为泛型让它只接受 Integer 的类型。</p>
<p>所以，综合上面信息，我们可以得到下面的结论。</p>
<p>与普通的 Object 代替一切类型这样简单粗暴而言，泛型使得数据的类别可以像参数一样由外部传递进来。它提供了一种扩展能力。它更符合面向抽象开发的软件编程宗旨。<br>当具体的类型确定后，泛型又提供了一种类型检测的机制，只有相匹配的数据才能正常的赋值，否则编译器就不通过。所以说，它是一种类型安全检测机制，一定程度上提高了软件的安全性防止出现低级的失误。<br>泛型提高了程序代码的可读性，不必要等到运行的时候才去强制转换，在定义或者实例化阶段，因为<code>Cache&lt;String&gt;</code>这个类型显化的效果，程序员能够一目了然猜测出代码要操作的数据类型。</p>
<p>下面的文章，我们正常介绍泛型的相关知识。</p>
<p>泛型的定义和使用<br>泛型按照使用情况可以分为 3 种。</p>
<ul>
<li>泛型类。</li>
<li>泛型方法。</li>
<li>泛型接口。</li>
</ul>
<p>###泛型类</p>
<p>我们可以这样定义一个泛型类。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">	T field1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>尖括号 &lt;&gt;中的 T 被称作是类型参数，用于指代任何类型。事实上，T 只是一种习惯性写法，如果你愿意。你可以这样写。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span>&lt;<span class="title">Hello</span>&gt; </span>&#123;</span><br><span class="line">	Hello field1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>但出于规范的目的，Java 还是建议我们用单个大写字母来代表类型参数。常见的如：</p>
<p>T 代表一般的任何类。<br>E 代表 Element 的意思，或者 Exception 异常的意思。<br>K 代表 Key 的意思。<br>V 代表 Value 的意思，通常与 K 一起配合使用。<br>S 代表 Subtype 的意思，文章后面部分会讲解示意。<br>如果一个类被 <t>的形式定义，那么它就被称为是泛型类。</t></p>
<p>那么对于泛型类怎么样使用呢？<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Test&lt;String&gt; test1 = <span class="keyword">new</span> Test&lt;&gt;();</span><br><span class="line">Test&lt;Integer&gt; test2 = <span class="keyword">new</span> Test&lt;&gt;();</span><br></pre></td></tr></table></figure></p>
<p>只要在对泛型类创建实例的时候，在尖括号中赋值相应的类型便是。T 就会被替换成对应的类型，如 String 或者是 Integer。你可以相像一下，当一个泛型类被创建时，内部自动扩展成下面的代码。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span>&lt;<span class="title">String</span>&gt; </span>&#123;</span><br><span class="line">	String field1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>当然，泛型类不至接受一个类型参数，它还可以这样接受多个类型参数。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MultiType</span> &lt;<span class="title">E</span>,<span class="title">T</span>&gt;</span>&#123;</span><br><span class="line">	E value1;</span><br><span class="line">	T value2;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> E <span class="title">getValue1</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> value1;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> T <span class="title">getValue2</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> value2;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>###泛型方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test1</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">testMethod</span><span class="params">(T t)</span></span>&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>泛型方法与泛型类稍有不同的地方是，类型参数也就是尖括号那一部分是写在返回值前面的。<t>中的 T 被称为类型参数，而方法中的 T 被称为参数化类型，它不是运行时真正的参数。</t></p>
<p>当然，声明的类型参数，其实也是可以当作返回值的类型的。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span>  &lt;T&gt; <span class="function">T <span class="title">testMethod1</span><span class="params">(T t)</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>泛型类与泛型方法的共存现象<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test1</span>&lt;<span class="title">T</span>&gt;</span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span>  <span class="keyword">void</span> <span class="title">testMethod</span><span class="params">(T t)</span></span>&#123;</span><br><span class="line">		System.out.println(t.getClass().getName());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">public</span>  &lt;T&gt; <span class="function">T <span class="title">testMethod1</span><span class="params">(T t)</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> t;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，Test1<t>是泛型类，testMethod 是泛型类中的普通方法，而 testMethod1 是一个泛型方法。而泛型类中的类型参数与泛型方法中的类型参数是没有相应的联系的，泛型方法始终以自己定义的类型参数为准。</t></p>
<p>所以，针对上面的代码，我们可以这样编写测试代码。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Test1&lt;String&gt; t = <span class="keyword">new</span> Test1();</span><br><span class="line">t.testMethod(<span class="string">"generic"</span>);</span><br><span class="line">Integer i = t.testMethod1(<span class="keyword">new</span> Integer(<span class="number">1</span>));</span><br></pre></td></tr></table></figure></p>
<p>泛型类的实际类型参数是 String，而传递给泛型方法的类型参数是 Integer，两者不想干。</p>
<p>但是，为了避免混淆，如果在一个泛型类中存在泛型方法，那么两者的类型参数最好不要同名。比如，Test1<t>代码可以更改为这样<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test1</span>&lt;<span class="title">T</span>&gt;</span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span>  <span class="keyword">void</span> <span class="title">testMethod</span><span class="params">(T t)</span></span>&#123;</span><br><span class="line">		System.out.println(t.getClass().getName());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">public</span>  &lt;E&gt; <span class="function">E <span class="title">testMethod1</span><span class="params">(E e)</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> e;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></t></p>
<p>###泛型接口</p>
<p>泛型接口和泛型类差不多，所以一笔带过。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Iterable</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>####通配符 ？</p>
<p>除了用 <t>表示泛型外，还有 &lt;?&gt;这种形式。？ 被称为通配符。</t></p>
<p>可能有同学会想，已经有了 <t>的形式了，为什么还要引进 &lt;?&gt;这样的概念呢？<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Base</span></span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sub</span> <span class="keyword">extends</span> <span class="title">Base</span></span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">Sub sub = <span class="keyword">new</span> Sub();</span><br><span class="line">Base base = sub;</span><br></pre></td></tr></table></figure></t></p>
<p>上面代码显示，Base 是 Sub 的父类，它们之间是继承关系，所以 Sub 的实例可以给一个 Base 引用赋值，那么</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Sub&gt; lsub = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">List&lt;Base&gt; lbase = lsub;</span><br></pre></td></tr></table></figure>
<p>最后一行代码成立吗？编译会通过吗？</p>
<p>答案是否定的。</p>
<p>编译器不会让它通过的。Sub 是 Base 的子类，不代表 List<sub>和 List<base>有继承关系。</sub></p>
<p>但是，在现实编码中，确实有这样的需求，希望泛型能够处理某一范围内的数据类型，比如某个类和它的子类，对此 Java 引入了通配符这个概念。</p>
<p>所以，通配符的出现是为了指定泛型中的类型范围。</p>
<p>通配符有 3 种形式。</p>
<ul>
<li>&lt;?&gt;被称作无限定的通配符。</li>
<li>&lt;? extends T&gt;被称作有上限的通配符。</li>
<li>&lt;? super T&gt;被称作有下限的通配符。</li>
</ul>
<p>###无限定通配符 &lt;?&gt;</p>
<p>无限定通配符经常与容器类配合使用，它其中的 ? 其实代表的是未知类型，所以涉及到 ? 时的操作，一定与具体类型无关。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testWildCards</span><span class="params">(Collection&lt;?&gt; collection)</span></span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的代码中，方法内的参数是被无限定通配符修饰的 Collection 对象，它隐略地表达了一个意图或者可以说是限定，那就是 testWidlCards() 这个方法内部无需关注 Collection 中的真实类型，因为它是未知的。所以，你只能调用 Collection 中与类型无关的方法。</p>
<p>我们可以看到，当 &lt;?&gt;存在时，Collection 对象丧失了 add() 方法的功能，编译器不通过。<br>我们再看代码。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;?&gt; wildlist = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">wildlist.add(<span class="number">123</span>);<span class="comment">// 编译不通过</span></span><br></pre></td></tr></table></figure></p>
<p>有人说，&lt;?&gt;提供了只读的功能，也就是它删减了增加具体类型元素的能力，只保留与具体类型无关的功能。它不管装载在这个容器内的元素是什么类型，它只关心元素的数量、容器是否为空？我想这种需求还是很常见的吧。</p>
<p>有同学可能会想，&lt;?&gt;既然作用这么渺小，那么为什么还要引用它呢？ </p>
<p>个人认为，提高了代码的可读性，程序员看到这段代码时，就能够迅速对此建立极简洁的印象，能够快速推断源码作者的意图。</p>
<p>###&lt;? extends T&gt;</p>
<p>&lt;?&gt;代表着类型未知，但是我们的确需要对于类型的描述再精确一点，我们希望在一个范围内确定类别，比如类型 A 及 类型 A 的子类都可以。</p>
<p>&lt;? extends T&gt; 代表类型 T 及 T 的子类。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSub</span><span class="params">(Collection&lt;? extends Base&gt; para)</span></span>&#123; &#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，para 这个 Collection 接受 Base 及 Base 的子类的类型。 但是，它仍然丧失了写操作的能力。也就是说<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">para.add(<span class="keyword">new</span> Sub()); para.add(<span class="keyword">new</span> Base());</span><br></pre></td></tr></table></figure></p>
<p>仍然编译不通过。 没有关系，我们不知道具体类型，但是我们至少清楚了类型的范围。</p>
<h3 id="lt-super-T-gt-这个和-lt-extends-T-gt-相对应，代表-T-及-T-的超类。"><a href="#lt-super-T-gt-这个和-lt-extends-T-gt-相对应，代表-T-及-T-的超类。" class="headerlink" title="&lt;? super T&gt; 这个和 &lt;? extends T&gt;相对应，代表 T 及 T 的超类。"></a><code>&lt;? super T&gt;</code> 这个和 <code>&lt;? extends T&gt;</code>相对应，代表 T 及 T 的超类。</h3> <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSuper</span><span class="params">(Collection&lt;? <span class="keyword">super</span> Sub&gt; para)</span></span>&#123; &#125;</span><br></pre></td></tr></table></figure>
<p> <code>&lt;? super T&gt;</code>神奇的地方在于，它拥有一定程度的写操作的能力。<br>  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSuper</span><span class="params">(Collection&lt;? <span class="keyword">super</span> Sub&gt; para)</span></span>&#123; para.add(<span class="keyword">new</span> Sub());<span class="comment">//编译通过 para.add(new Base());//编译不通过 &#125;</span></span><br></pre></td></tr></table></figure></p>
<h1 id="通配符与类型参数的区别"><a href="#通配符与类型参数的区别" class="headerlink" title="通配符与类型参数的区别"></a>通配符与类型参数的区别</h1><p>一般而言，通配符能干的事情都可以用类型参数替换。 比如<br>  <code>java public void testWildCards(Collection&lt;?&gt; collection){}</code><br>可以被<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(Collection&lt;T&gt; collection)</span></span>&#123;&#125;</span><br></pre></td></tr></table></figure></p>
<p>取代。</p>
<p>值得注意的是，如果用泛型方法来取代通配符，那么上面代码中 collection 是能够进行写操作的。只不过要进行强制转换。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(Collection&lt;T&gt; collection)</span></span>&#123;</span><br><span class="line">	collection.add((T)<span class="keyword">new</span> Integer(<span class="number">12</span>));</span><br><span class="line">	collection.add((T)<span class="string">"123"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>需要特别注意的是，类型参数适用于参数之间的类别依赖关系，举例说明。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test2</span> &lt;<span class="title">T</span>,<span class="title">E</span> <span class="keyword">extends</span> <span class="title">T</span>&gt;</span>&#123;</span><br><span class="line">	T value1;</span><br><span class="line">	E value2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> &lt;D,S extends D&gt; <span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(D d,S s)</span></span>&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<p>E 类型是 T 类型的子类，显然这种情况类型参数更适合。<br>有一种情况是，通配符和类型参数一起使用。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">test</span><span class="params">(T t,Collection&lt;? extends T&gt; collection)</span></span>&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>如果一个方法的返回类型依赖于参数的类型，那么通配符也无能为力。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">test1</span><span class="params">(T t)</span></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> value1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>###类型擦除</p>
<p>泛型是 Java 1.5 版本才引进的概念，在这之前是没有泛型的概念的，但显然，泛型代码能够很好地和之前版本的代码很好地兼容。</p>
<p>这是因为，泛型信息只存在于代码编译阶段，在进入 JVM 之前，与泛型相关的信息会被擦除掉，专业术语叫做类型擦除。</p>
<p>通俗地讲，泛型类和普通类在 java 虚拟机内是没有什么特别的地方。回顾文章开始时的那段代码<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; l1 = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">List&lt;Integer&gt; l2 = <span class="keyword">new</span> ArrayList&lt;Integer&gt;();</span><br><span class="line">		</span><br><span class="line">System.out.println(l1.getClass() == l2.getClass());</span><br></pre></td></tr></table></figure></p>
<p>打印的结果为 true 是因为 List<string>和 List<integer>在 jvm 中的 Class 都是 List.class。</integer></string></p>
<p>泛型信息被擦除了。</p>
<p>可能同学会问，那么类型 String 和 Integer 怎么办？</p>
<p>答案是泛型转译。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Erasure</span> &lt;<span class="title">T</span>&gt;</span>&#123;</span><br><span class="line">	T object;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Erasure</span><span class="params">(T object)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.object = object;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Erasure 是一个泛型类，我们查看它在运行时的状态信息可以通过反射。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Erasure&lt;String&gt; erasure = <span class="keyword">new</span> Erasure&lt;String&gt;(<span class="string">"hello"</span>);</span><br><span class="line">Class eclz = erasure.getClass();</span><br><span class="line">System.out.println(<span class="string">"erasure class is:"</span>+eclz.getName());</span><br></pre></td></tr></table></figure></p>
<p>打印的结果是</p>
<p><code>erasure class is:com.frank.test.Erasure</code></p>
<p>Class 的类型仍然是 Erasure 并不是 Erasure<t>这种形式，那我们再看看泛型类中 T 的类型在 jvm 中是什么具体类型。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Field[] fs = eclz.getDeclaredFields();</span><br><span class="line"><span class="keyword">for</span> ( Field f:fs) &#123;</span><br><span class="line">	System.out.println(<span class="string">"Field name "</span>+f.getName()+<span class="string">" type:"</span>+f.getType().getName());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></t></p>
<p>打印结果是<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Field name object type:java.lang.Object</span><br></pre></td></tr></table></figure></p>
<p>那我们可不可以说，泛型类被类型擦除后，相应的类型就被替换成 Object 类型呢？</p>
<p>这种说法，不完全正确。</p>
<p>我们更改一下代码。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public class Erasure &lt;T extends String&gt;&#123;</span><br><span class="line">//	public class Erasure &lt;T&gt;&#123;</span><br><span class="line">	T object;</span><br><span class="line"></span><br><span class="line">	public Erasure(T object) &#123;</span><br><span class="line">		this.object = object;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>现在再看测试结果：</p>
<p><code>Field name object type:java.lang.String</code></p>
<p>我们现在可以下结论了，在泛型类被类型擦除的时候，之前泛型类中的类型参数部分如果没有指定上限，如 <t>则会被转译成普通的 Object 类型，如果指定了上限如 <t extends string>则类型参数就被替换成类型上限。</t></t></p>
<p>所以，在反射中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Erasure</span> &lt;<span class="title">T</span>&gt;</span>&#123;</span><br><span class="line">	T object;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Erasure</span><span class="params">(T object)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.object = object;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(T object)</span></span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>add() 这个方法对应的 Method 的签名应该是 <code>Object.class</code>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">Erasure&lt;String&gt; erasure = <span class="keyword">new</span> Erasure&lt;String&gt;(<span class="string">"hello"</span>);</span><br><span class="line"></span><br><span class="line">Class eclz = erasure.getClass();</span><br><span class="line"></span><br><span class="line">System.out.println(<span class="string">"erasure class is:"</span>+eclz.getName());</span><br><span class="line"></span><br><span class="line">Method[] methods = eclz.getDeclaredMethods();</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> ( Method m:methods )&#123;</span><br><span class="line"></span><br><span class="line">	System.out.println(<span class="string">" method:"</span>+m.toString());</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>打印结果是</p>
<p> <code>method:public void com.frank.test.Erasure.add(java.lang.Object)</code></p>
<p>也就是说，如果你要在反射中找到 add 对应的 Method，你应该调用 getDeclaredMethod(“add”,Object.class)否则程序会报错，提示没有这么一个方法，原因就是类型擦除的时候，T 被替换成 Object 类型了。</p>
<p>类型擦除带来的局限性<br>类型擦除，是泛型能够与之前的 java 版本代码兼容共存的原因。但也因为类型擦除，它会抹掉很多继承相关的特性，这是它带来的局限性。</p>
<p>理解类型擦除有利于我们绕过开发当中可能遇到的雷区，同样理解类型擦除也能让我们绕过泛型本身的一些限制。比如</p>
<p>正常情况下，因为泛型的限制，编译器不让最后一行代码编译通过，因为类似不匹配，但是，基于对类型擦除的了解，利用反射，我们可以绕过这个限制。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">Collection</span>&lt;<span class="title">E</span>&gt;</span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面是 List 和其中的 add() 方法的源码定义。</p>
<p>因为 E 代表任意的类型，所以类型擦除时，add 方法其实等同于</p>
<p>​    <code>boolean add(Object obj);</code></p>
<p>那么，利用反射，我们绕过编译器去调用 add 方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ToolTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; ls = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        ls.add(<span class="number">23</span>);</span><br><span class="line">        <span class="comment">//ls.add("text");</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Method method = ls.getClass().getDeclaredMethod(<span class="string">"add"</span>,Object.class);</span><br><span class="line">        	method.invoke(ls,<span class="number">42.9f</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchMethodException e) &#123;</span><br><span class="line">            <span class="comment">// TODO Auto-generated catch block</span></span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (SecurityException e) &#123;</span><br><span class="line">            <span class="comment">// TODO Auto-generated catch block</span></span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">            <span class="comment">// TODO Auto-generated catch block</span></span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IllegalArgumentException e) &#123;</span><br><span class="line">            <span class="comment">// TODO Auto-generated catch block</span></span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InvocationTargetException e) &#123;</span><br><span class="line">            <span class="comment">// TODO Auto-generated catch block</span></span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> ( Object o: ls)&#123;</span><br><span class="line">            System.out.println(o);</span><br><span class="line">        &#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>打印结果是：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">23</span><br><span class="line">test</span><br><span class="line">42.9</span><br></pre></td></tr></table></figure>
<p>可以看到，利用类型擦除的原理，用反射的手段就绕过了正常开发中编译器不允许的操作限制。</p>
<p>泛型中值得注意的地方<br>泛型类或者泛型方法中，不接受 8 种基本数据类型。<br>所以，你没有办法进行这样的编码。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;<span class="keyword">int</span>&gt; li = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">List&lt;<span class="keyword">boolean</span>&gt; li = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br></pre></td></tr></table></figure>
<p>需要使用它们对应的包装类。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Integer&gt; li = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">List&lt;Boolean&gt; li1 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br></pre></td></tr></table></figure>
<p>对泛型方法的困惑</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">T <span class="title">test</span><span class="params">(T t)</span></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>有的同学可能对于连续的两个 T 感到困惑，其实 <t>是为了说明类型参数，是声明,而后面的不带尖括号的 T 是方法的返回值类型。<br>你可以相像一下，如果 test() 这样被调用</t></p>
<p><code>test(&quot;123&quot;);</code><br>那么实际上相当于</p>
<p><code>public String test(String t);</code><br>Java 不能创建具体类型的泛型数组<br>这句话可能难以理解，代码说明。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Integer&gt;[] li2 = <span class="keyword">new</span> ArrayList&lt;Integer&gt;[];</span><br><span class="line">List&lt;Boolean&gt; li3 = <span class="keyword">new</span> ArrayList&lt;Boolean&gt;[];</span><br></pre></td></tr></table></figure>
<p>这两行代码是无法在编译器中编译通过的。原因还是类型擦除带来的影响。</p>
<p>List<integer>和 List<boolean>在 jvm 中等同于List<object>，所有的类型信息都被擦除，程序也无法分辨一个数组中的元素类型具体是 List<integer>类型还是 List<boolean>类型。</boolean></integer></object></boolean></integer></p>
<p>但是，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">List&lt;?&gt;[] li3 = <span class="keyword">new</span> ArrayList&lt;?&gt;[<span class="number">10</span>];</span><br><span class="line">li3[<span class="number">1</span>] = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">List&lt;?&gt; v = li3[<span class="number">1</span>];</span><br></pre></td></tr></table></figure>
<p>借助于无限定通配符却可以，前面讲过 ？代表未知类型，所以它涉及的操作都基本上与类型无关，因此 jvm 不需要针对它对类型作判断，因此它能编译通过，但是，只提供了数组中的元素因为通配符原因，它只能读，不能写。比如，上面的 v 这个局部变量，它只能进行 get() 操作，不能进行 add() 操作，这个在前面通配符的内容小节中已经讲过。</p>
<p><strong>泛型，并不神奇</strong><br>我们可以看到，泛型其实并没有什么神奇的地方，泛型代码能做的非泛型代码也能做。</p>
<p>而类型擦除，是泛型能够与之前的 java 版本代码兼容共存的原因。</p>
<p>可量也正因为类型擦除导致了一些隐患与局限。</p>
<p>但，我还是要建议大家使用泛型，如官方文档所说的，如果可以使用泛型的地方，尽量使用泛型。</p>
<p>毕竟它抽离了数据类型与代码逻辑，本意是提高程序代码的简洁性和可读性，并提供可能的编译时类型转换安全检测功能。</p>
<p>类型擦除不是泛型的全部，但是它却能很好地检测我们对于泛型这个概念的理解程度。</p>
<p>我在文章开头将泛型比作是一个守门人，原因就是他本意是好的，守护我们的代码安全，然后在门牌上写着出入的各项规定，及“xxx 禁止出入”的提醒。但是同我们日常所遇到的那些门卫一般，他们古怪偏执，死板守旧，我们可以利用反射基于类型擦除的认识，来绕过泛型中某些限制，现实生活中，也总会有调皮捣蛋者能够基于对门卫们生活作息的规律，选择性地绕开他们的监视，另辟蹊径溜进或者溜出大门，然后扬长而去，剩下守卫者一个孤独的身影。</p>
<h2 id="所以，我说泛型，并不神秘，也不神奇。"><a href="#所以，我说泛型，并不神秘，也不神奇。" class="headerlink" title="所以，我说泛型，并不神秘，也不神奇。"></a>所以，我说泛型，并不神秘，也不神奇。</h2><p>作者：frank909<br>来源：CSDN<br>原文：<a href="https://blog.csdn.net/briblue/article/details/76736356" target="_blank" rel="noopener">https://blog.csdn.net/briblue/article/details/76736356</a><br>版权声明：本文为博主原创文章，转载请附上博文链接！</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/03/22/java/细说 Java 的深拷贝和浅拷贝/" rel="next" title="细说java的深拷贝和浅拷贝">
                <i class="fa fa-chevron-left"></i> 细说java的深拷贝和浅拷贝
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/22/java/java的线程的停止方式/" rel="prev" title="java线程停止方式">
                java线程停止方式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">xiezc</p>
              <p class="site-description motion-element" itemprop="description">主要一些技术文章, 有些文章是转载的</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">72</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#lt-super-T-gt-这个和-lt-extends-T-gt-相对应，代表-T-及-T-的超类。"><span class="nav-number">1.</span> <span class="nav-text">&lt;? super T&gt; 这个和 &lt;? extends T&gt;相对应，代表 T 及 T 的超类。</span></a></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#通配符与类型参数的区别"><span class="nav-number"></span> <span class="nav-text">通配符与类型参数的区别</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#所以，我说泛型，并不神秘，也不神奇。"><span class="nav-number"></span> <span class="nav-text">所以，我说泛型，并不神秘，也不神奇。</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xiezc</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("eRAHvO0xVYwckgdXIVpfugRG-gzGzoHsz", "57lKp708hde92YeG1xX9MQj1");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
